package com.hao.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.hao.springcloud.dao.PaymentDao;
import com.hao.springcloud.entities.Payment;
import com.hao.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.sun.xml.internal.bind.v2.model.core.ID;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * TODO
 *
 * @author 97472
 * @version 1.0
 * @date 2022/1/4 16:08
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    private PaymentDao paymentDao;

    @Override
    public int add(Payment payment) {
        return paymentDao.add(payment);
    }

    @Override
    public Payment getPaymentById(Long id) {
        return paymentDao.getPaymentById(id);
    }

    @Override
    @HystrixCommand(fallbackMethod = "paymentInfo_OKHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_OK(Integer id) {
        return "线程池："+Thread.currentThread().getName()+"paymentInfo_OK,ID:"+ id;
    }

    @Override
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_TimeOut(Integer id) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池："+Thread.currentThread().getName()+"paymentInfo_TimeOut,ID:"+ id;
    }

    @Override
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerHandler",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启熔断器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求的次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),// 时间窗口
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")// 失败率多少后跳匝
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0){
            throw  new RuntimeException("id can't be negative number");
        }
        String uuid = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"  调用成功，id："+uuid;
    }

    public String paymentInfo_TimeOutHandler(Integer id) {
        return "线程池："+Thread.currentThread().getName()+"paymentInfo_TimeOutHandler,ID:"+ id;

    }
    public String paymentInfo_OKHandler(Integer id) {
        return "线程池："+Thread.currentThread().getName()+"paymentInfo_OKHandler,ID:"+ id;
    }

    public String paymentCircuitBreakerHandler(Integer id) {
        return" id can't be negative number !";
    }
}
